package com.hserver.docker.controller;

import com.hserver.docker.bean.Deploy;
import com.hserver.docker.bean.Record;
import com.hserver.docker.config.ConstConfig;
import com.hserver.docker.service.DeployService;
import com.hserver.docker.service.DockerService;
import com.hserver.docker.service.RecordService;
import top.hserver.core.interfaces.HttpRequest;
import top.hserver.core.interfaces.HttpResponse;
import top.hserver.core.ioc.annotation.*;
import top.hserver.core.queue.HServerQueue;
import top.hserver.core.server.util.JsonResult;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 线上环境的后台服务自动化部署
 */
@Controller("/deploy/")
public class DeployController {

    @Autowired
    private DeployService deployService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private DockerService dockerService;

    /**
     * 添加项目页面
     */
    @RequestMapping(value = "new", method = RequestMethod.GET)
    public void newDeploy(HttpResponse response) {
        response.sendTemplate("deploy/new.ftl");
    }

    /**
     * 添加项目请求
     */
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public void insert(Deploy deploy, HttpResponse response) {
        String uuid;
        if (deploy.getUuid() != null && deploy.getUuid().trim().length() > 0) {
            uuid = deploy.getUuid();
            deployService.update(deploy);
        } else {
            uuid = UUID.randomUUID().toString();
            deploy.setUuid(uuid);
            deployService.insert(deploy);
        }
        response.redirect("/deploy/detail/" + uuid);
    }

    /**
     * 详情页面
     */
    @RequestMapping(value = "detail/{uuid}", method = RequestMethod.GET)
    public void detail(HttpRequest request, HttpResponse response) {
        Map<String, Object> data = new HashMap<>(1);
        data.put("detail", deployService.getDeploy(request.query("uuid")));
        data.put("recordList", recordService.getList(request.query("uuid")));
        response.sendTemplate("deploy/detail.ftl", data);
    }

    @GET(value = "edit/{uuid}")
    public void edit(HttpRequest request, HttpResponse response) {
        Map<String, Object> data = new HashMap<>(1);
        data.put("detail", deployService.getDeploy(request.query("uuid")));
        response.sendTemplate("deploy/new.ftl", data);
    }

    @RequestMapping(value = "del/{uuid}", method = RequestMethod.GET)
    public void del(HttpRequest request, HttpResponse response) {
        deployService.del(request.query("uuid"));
        response.redirect("/");
    }

    @RequestMapping(value = "deploy/{uuid}", method = {RequestMethod.POST, RequestMethod.GET, RequestMethod.PUT})
    public JsonResult deploy(HttpRequest request) throws IOException {
        String uuid = request.query("uuid");
        if (uuid != null && deployService.checkSource(request, uuid)) {
            String id = UUID.randomUUID().toString();
            HServerQueue.sendQueue("deploy", uuid, id);
            return JsonResult.ok().put("recordId", id);
        } else {
            return JsonResult.error("部署条件不满足");
        }
    }


    @RequestMapping(value = "restart", method = {RequestMethod.POST})
    public JsonResult restart(String uuid) throws IOException {
        dockerService.runContainer(uuid);
        return JsonResult.ok();
    }

    @RequestMapping(value = "stop", method = {RequestMethod.POST})
    public JsonResult stop(String uuid) throws IOException {
        dockerService.stopContainer(uuid);
        return JsonResult.ok();
    }

    @RequestMapping(value = "remove", method = {RequestMethod.POST})
    public JsonResult remove(String uuid) throws IOException {
        dockerService.stopContainer(uuid);
        dockerService.removeContainer(uuid);
        return JsonResult.ok();
    }

    /**
     * 回滚指定的ID部署
     *
     * @param uuid
     * @param recordId
     * @throws IOException
     */
    @GET(value = "rollback/{uuid}/{recordId}")
    public JsonResult rollback(String uuid, String recordId) throws IOException {
        try {
            dockerService.runRollBackContainer(uuid, recordId);
        } catch (Exception e) {
            return JsonResult.error();
        }
        return JsonResult.ok();
    }


    @RequestMapping(value = "status", method = {RequestMethod.POST})
    public JsonResult status(String uuid) throws IOException {
        return JsonResult.ok().put("data", dockerService.infoContainer(uuid));
    }


    /**
     * 下载
     */
    @RequestMapping(value = "downloadLog/{recordId}", method = RequestMethod.GET)
    public void downloadLog(String recordId, HttpResponse response) {
        if (recordId != null) {
            response.setDownloadFile(new File(ConstConfig.LOG_PATH + recordId + ".log"));
        } else {
            response.sendText("下载失败");
        }
    }


    /**
     * remove
     */
    @RequestMapping(value = "remove/{recordId}", method = RequestMethod.GET)
    public void remove(String recordId, HttpResponse response) {
        try {
            //删除镜像
            try {
                dockerService.removeImage(recordId);
            } catch (Exception e) {
                response.redirect("/");
            }
            Record byId = recordService.getById(recordId);
            //删除日志
            new File(ConstConfig.LOG_PATH + recordId + ".log").delete();
            //删除record
            recordService.removeId(recordId);
            Map<String, Object> data = new HashMap<>(2);
            data.put("detail", deployService.getDeploy(byId.getUuid()));
            data.put("recordList", recordService.getList(byId.getUuid()));
            response.sendTemplate("deploy/detail.ftl", data);
        } catch (Exception e) {
            response.redirect("/");
        }
    }

}
